package com.mutual.commom.util;

//import com.hexin.common.utils.other.ValidateUtil;

//import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

/**
 * User: Ren yulin Date: 13-4-23 下午4:11 日期处理
 */
public class DateUtil {
    public static Logger logger = Logger.getLogger(DateUtil.class);
    public static final String pattern = "yyyy-MM-dd HH:mm:ss";
    private static final int MONTHS_ONE_YEAR = 12;

    /**
     * 获取两个日期之间的天数
     *
     * @param beginDateStr
     * @param endDateStr
     * @return
     */
    public static long getDaySub(String beginDateStr, String endDateStr) {
        long day = 0;
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
        java.util.Date beginDate;
        java.util.Date endDate;
        try {
            beginDate = format.parse(beginDateStr);
            endDate = format.parse(endDateStr);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            // TODO 自动生成 catch 块
            logger.error("DateUtil   getDaySub方法出错，异常信息为:", e);
        }
        return day;
    }

    public static long getDaySub(String beginDateStr, String endDateStr, String pattern) {
        long day = 0;
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(pattern);
        java.util.Date beginDate;
        java.util.Date endDate;
        try {
            beginDate = format.parse(beginDateStr);
            endDate = format.parse(endDateStr);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
        } catch (ParseException e) {
            // TODO 自动生成 catch 块
            logger.error("DateUtil   getDaySub方法出错，异常信息为:", e);
        }
        return day;
    }

    /**
     * 日期增加
     *
     * @param date
     * @param column
     * @param value
     * @return
     */
    public static Date addDate(Date date, int column, int value) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(column, value);
        return calendar.getTime();
    }

    public static Date long2Date(long time) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date(time));
        return calendar.getTime();
    }

    public static Date string2Date(String str) throws ParseException {
        if (str == null || "".equals(str)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.parse(str);
    }

    public static Date string2Date(String str, String pattern) {
        if (str == null || "".equals(str)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            return simpleDateFormat.parse(str);
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date dateFormatChange(Date date, String format) {
        SimpleDateFormat simpleDateFormatOne = new SimpleDateFormat(format);
        SimpleDateFormat simpleDateFormatTow = new SimpleDateFormat(format);
        String day = simpleDateFormatOne.format(date);
        try {
            return simpleDateFormatTow.parse(day);
        } catch (ParseException e) {
            logger.error("DateUtil   dateFormatChange方法出错，异常信息为:", e);
            return null;
        }
    }

    public static Date getCurrentDate(String value) {
        if (value == null || "".equals(value)) {
            value = pattern;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(value);
        String time = simpleDateFormat.format(new Date());
        try {
            return simpleDateFormat.parse(time);
        } catch (ParseException e) {
            return null;
        }
    }

    // ***************************************************
    // 名称：dateToStr
    // 功能：将指定的日期转换成字符串
    // 输入：aDteValue: 要转换的日期;
    // aFmtDate: 转换日期的格式, 默认为:"yyyy/MM/dd"
    // 输出：
    // 返回：转换之后的字符串
    // ***************************************************
    public static String dateToStr(Date aDteValue, String aFmtDate) {
        String strRtn = null;

        if (aDteValue == null) {
            return "";
        }
        if (aFmtDate.length() == 0) {
            aFmtDate = "yyyy-MM-dd";
        }
        Format fmtDate = new SimpleDateFormat(aFmtDate);
        try {
            strRtn = fmtDate.format(aDteValue);
        } catch (Exception e) {

        }

        return (strRtn);
    }

    public static Calendar string2Calendar(String str, String pattern) {
        if (str == null || "".equals(str)) {
            return null;
        }
        Date date = null;
        date = string2Date(str, pattern);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar;
    }

    public static String date2String(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    /**
     * 获取当前的日期和时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getDateTime() {
        String strCurrentDateTime = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        strCurrentDateTime = formatter.format(currentDateTime);
        return strCurrentDateTime;
    }

    /**
     * 获取当前的日期和时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getTimeHHmm() {
        String strCurrentDateTime = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        strCurrentDateTime = formatter.format(currentDateTime);
        return strCurrentDateTime;
    }

    /**
     * 获取当前的日期的前一天和时间，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String getDateTimeBeforeDay() {
        Calendar caldate = Calendar.getInstance();
        String strCurrentDateTime = "";
        caldate.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        strCurrentDateTime = formatter.format(caldate.getTime());
        return strCurrentDateTime;
    }

    /**
     * @param pattern yyyy-MM-dd ..
     * @return
     */
    public static String getDateTimeBeforeDay(String pattern) {
        Calendar caldate = Calendar.getInstance();
        String strCurrentDateTime = "";
        caldate.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        strCurrentDateTime = formatter.format(caldate.getTime());
        return strCurrentDateTime;
    }


    /**
     * 获取当前年月日组成的字符串，格式为yyyyMMdd
     *
     * @return
     */
    public static String getYMD() {
        String strYMD = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        strYMD = formatter.format(currentDateTime);
        return strYMD;
    }

    /**
     * 获取当前年月日组成的字符串，格式为yyyy-MM-dd
     *
     * @return
     */
    public static String getDay() {
        String strYMD = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        strYMD = formatter.format(currentDateTime);
        return strYMD;
    }

    /**
     * 获取当前年月日组成的字符串，格式为yyyy-MM-dd
     *
     * @return
     */
    public static String getDayBeforeMonth() {
        String strYMD = "";
        Date currentDateTime = new Date();// 得到当前系统时间
        Calendar calendar = Calendar.getInstance();// 日历对象
        calendar.setTime(currentDateTime);// 设置当前日期
        calendar.add(Calendar.MONTH, -1);// 月份减一
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(calendar.getTime());
    }


    /**
     * 获取某个日期的天
     *
     * @return
     */
    public static int getDayOfMonth(Date date) {
        String day = "";
        Date currentDateTime = new Date();// 得到当前系统时间
        Calendar calendar = Calendar.getInstance();// 日历对象
        calendar.setTime(currentDateTime);// 设置当前日期
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取当前年字符串，格式为yyyy
     *
     * @return
     */
    public static String getMonth() {
        String strYMD = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        strYMD = formatter.format(currentDateTime);
        return strYMD;
    }

    /**
     * 获取当前月字符串，格式为yyyy
     *
     * @return
     */
    public static String getYear() {
        String strYMD = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        strYMD = formatter.format(currentDateTime);
        return strYMD;
    }

    public static String getYear(String date) {
        if (StringUtils.isEmpty(date)) return null;
        date = date.trim();
        return date.substring(0, 4);
    }

    /**
     * 获取当前年月日时分秒组成的字符串，格式为yyyyMMddHHmmss
     *
     * @return
     */
    public static String getYMDHMS() {
        String strYMDHMS = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        strYMDHMS = formatter.format(currentDateTime);
        return strYMDHMS;
    }

    /**
     * 获取当前年月日时分秒毫秒组成的字符串，格式为yyyyMMddHHmmssSSS
     *
     * @return
     */
    public static String getYMDHMSS() {
        String strYMDHMSS = "";
        Date currentDateTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        strYMDHMSS = formatter.format(currentDateTime);
        return strYMDHMSS;
    }

    // 得到对比月变化的目标年月
    //getMonthChange("2003-10-09",1)="2003-11-09";
    //getMonthChange("2003-10-09",-2)="2003-08-09";

    /**
     * 返回变化给定月份量的时间值，并格式化为yyyy-MM-dd的时间字符串。<br>
     * 如：getMonthChange("2003-10-09",1)="2003-11-09"，<br>
     * getMonthChange("2003-10-09",-2)="2003-08-09"。
     *
     * @param strCurrentTime 格式化为yyyy-MM-dd的时间String
     * @param iQuantity      添加的月份时间量
     * @return 更改日期后的时间值，格式化yyyy-MM-dd的时间字符串
     */
    public static String getMonthChange(String strCurrentTime, int iQuantity) {
        String strTarget = "";
        int iYear = Integer.parseInt(strCurrentTime.substring(0, 4));
        int iMonth = Integer.parseInt(strCurrentTime.substring(5, 7));
        int iDay = Integer.parseInt(strCurrentTime.substring(8, 10));
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, iYear);
        cal.set(Calendar.MONTH, iMonth - 1);
        cal.set(Calendar.DAY_OF_MONTH, iDay);
        cal.add(Calendar.MONTH, iQuantity);
        Date currentDate = cal.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        strTarget = formatter.format(currentDate);
        return strTarget;
    }
    //-----------------------------------------------------------------------------------
    // 得到对比日期变化的目标日期
    // getDateChange("2003-10-15",1)="2003-10-16";
    //getDateChange("2003-10-15",-2)="2003-10-13";

    /**
     * 返回变化给定日期量的时间值，并格式化为yyyy-MM-dd的时间字符串。<br>
     * 如：getDateChange("2003-10-15",1)="2003-10-16"，<br>
     * getDateChange("2003-10-15",-2)="2003-10-13"
     *
     * @param strCurrentDate 格式化为yyyy-MM-dd的时间String
     * @param iQuantity      添加的日期时间量
     * @return 更改日期后的时间值，格式化yyyy-MM-dd的时间字符串
     */
    public static String getDateChange(String strCurrentDate, int iQuantity) {
        String strTarget = "";
        int iYear = Integer.parseInt(strCurrentDate.substring(0, 4));
        int iMonth = Integer.parseInt(strCurrentDate.substring(5, 7));
        int iDay = Integer.parseInt(strCurrentDate.substring(8, 10));

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, iYear);
        cal.set(Calendar.MONTH, iMonth - 1);
        cal.set(Calendar.DAY_OF_MONTH, iDay);
        cal.add(Calendar.DATE, iQuantity);
        Date currentDate = cal.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        strTarget = formatter.format(currentDate);
        return strTarget;
    }

    /**
     * 返回变化给定日期量的时间值，并格式化yyyy-MM-dd HH:mm:ss的时间字符串；日期为变化后的，时间为00：00：00。<br>
     * 如：getDateChange("2003-10-15",1)="2003-10-16 00:00:00"，<br>
     * getDateChange("2003-10-15",-2)="2003-10-13 00:00:00"
     *
     * @param strCurrentDate 格式化为yyyy-MM-dd的时间String
     * @param iQuantity      添加的日期时间量
     * @return 更改日期后的时间值，格式化yyyy-MM-dd HH:mm:ss的时间字符串；日期为变化后的，时间为23：59：59。
     */
    public static String getDateTimeChange(String strCurrentDate, int iQuantity) {
        String strTarget = "";
        int iYear = Integer.parseInt(strCurrentDate.substring(0, 4));
        int iMonth = Integer.parseInt(strCurrentDate.substring(5, 7));
        int iDay = Integer.parseInt(strCurrentDate.substring(8, 10));

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, iYear);
        cal.set(Calendar.MONTH, iMonth - 1);
        cal.set(Calendar.DAY_OF_MONTH, iDay);
        cal.add(Calendar.DATE, iQuantity);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date currentDate = cal.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        strTarget = formatter.format(currentDate);
        return strTarget;
    }

    /**
     * @param changeTime 改变的时间（分钟）
     * @return 当前时间前多久或者后多久，格式化yyyy-MM-dd HH:mm:ss的时间字符串。 比如：当前时间俩小时前 getNowTimeChange(-120) ，俩小时后getNowTimeChange(120)
     */
    public static String getNowTimeChange(int changeTime) {
        String strCurrentDateTime = "";
        Calendar caldate = null;
        Date currentDateTime = new Date();
        caldate = Calendar.getInstance();
        caldate.setTime(currentDateTime);
        currentDateTime = caldate.getTime();
        caldate.setTime(currentDateTime);
        caldate.add(Calendar.MINUTE, changeTime);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        strCurrentDateTime = formatter.format(caldate.getTime());
        return strCurrentDateTime;
    }

    /**
     * 日期的加减
     *
     * @param type   Y-年 M-月 D-天
     * @param amount 加减的数量
     * @return
     * @author wangjianhua
     */
//    public static Date modifyDate(Date date, String type, int amount) {
//        if (date == null) {
//            date = new Date();
//        }
//        if (ValidateUtil.isEmpty(type)) {
//            type = "";
//        }
//        Calendar now = Calendar.getInstance();
//        now.setTime(date);
//        // PubMethod.toPrint(now.get(Calendar.YEAR) + " " +
//        // (now.get(Calendar.MONTH)+1) + " " + now.get(Calendar.DAY_OF_YEAR) + "
//        // " + now.get(Calendar.DAY_OF_WEEK));
//        if ("Y".equalsIgnoreCase(type)) {
//            now.add(Calendar.YEAR, amount);
//        } else if ("M".equalsIgnoreCase(type)) {
//            now.add(Calendar.MONTH, amount);
//        } else if ("D".equalsIgnoreCase(type)) {
//            now.add(Calendar.DAY_OF_YEAR, amount);
//        }
//        return now.getTime();
//    }

    /**
     * 分钟的加减
     *
     * @param amount 加减的数量
     * @param format
     * @return
     * @author wanglx
     */
    public static String modifyMinute(Date date, int amount, String format) {

        if (date == null) {
            date = new Date();
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Calendar Cal = Calendar.getInstance();
        Cal.getTime();
        Cal.setTime(date);
        Cal.add(Calendar.MINUTE, amount);

        return formatter.format(Cal.getTime());
    }

    /**
     * 把格式为不同形式的时间字符串，去掉其中的"-"、" "和":"字符，转换为仅包含数字字符的时间字符串。 如：dateTimeFmtToStr("2011-04-15 16:54:33")="20110415165433"。
     *
     * @param dt 格式为不同形式的时间字符串，如：yyyy-MM-dd HH:mm:ss或yyyy-MM-dd等。
     * @return 仅包含数字字符的时间字符串，如：yyyyMMddHHmmss或yyyyMMdd。
     */
    public static String dateTimeFmtToStr(String dt) {
        if (dt == null || dt.equals("")) {
            return "";
        }
        String str = "";
        for (int i = 0; i < dt.length(); i++) {
            if (dt.charAt(i) == '-' || dt.charAt(i) == ' ' || dt.charAt(i) == ':') {
                continue;
            }
            str += dt.charAt(i);
        }
        return str;

    }

    /**
     * 获取两个日期之间相隔 时间
     */
    public static String datePlus(String startDate, String endDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 将截取到的时间字符串转化为时间格式的字符串
        Date beginTime;
        try {
            beginTime = sdf.parse(startDate);

            Date endtime = sdf.parse(endDate);
            // 默认为毫秒，除以1000是为了转换成秒
            long interval = (endtime.getTime() - beginTime.getTime()) / 1000;// 秒
            long day = interval / (24 * 3600);// 天
            long hour = interval % (24 * 3600) / 3600;// 小时
            long minute = interval % 3600 / 60;// 分钟
            long second = interval % 60;// 秒
            String str = "两个时间相差：" + day + "天" + hour + "小时" + minute + "分" + second + "秒";
            return str;
        } catch (ParseException e) {
            return "";
        }
    }

    /**
     * 获取Date
     *
     * @param timeStr timeStr
     * @return Date
     */
    public static Date getTime(String timeStr) {
        if (null == timeStr || timeStr.equals("")) {
            return null;
        }

        int length = timeStr.length();
        if (7 == length) {
            timeStr = timeStr + "-01 00:00:00";
        }
        if (10 == length) {
            timeStr = timeStr + " 00:00:00";
        }
        if (length > 7 && length < 10) {
            String[] str = timeStr.split("-");
            if (null == str || str.length != 3) {
                return null;
            }
            if (1 == str[1].length()) {
                str[1] = "0" + str[1];
            }
            if (1 == str[2].length()) {
                str[2] = "0" + str[2];
            }
            timeStr = str[0] + "-" + str[1] + "-" + str[2] + " 00:00:00";
        }
        DateFormat format = new SimpleDateFormat(pattern);
        String regex = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{2}:[0-9]{2}:[0-9]{2}";
        Pattern pattern = Pattern.compile(regex);
        if (!pattern.matcher(timeStr).matches()) {
            return null;
        }


        try {
            return format.parse(timeStr);
        } catch (Exception e) {
            logger.error("DateUtil   getTime方法出错，异常信息为:", e);
            return null;
        }
    }

    /**
     * 日期比较
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    public static int compare_date(String dateStart, String dateEnd) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dt1 = df.parse(dateStart);
            Date dt2 = df.parse(dateEnd);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 日期比较
     *
     * @param dateStart
     * @param dateEnd
     * @return
     */
    public static int compare_date_today(String dateStart, String dateEnd) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date dt1 = df.parse(dateStart);
            Date dt2 = df.parse(dateEnd);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


    public static int compare(Date dateStart, Date dateEnd) {
        try {
            if (dateStart.getTime() > dateEnd.getTime()) {
                return 1;
            } else if (dateStart.getTime() < dateEnd.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }


    public static int compare(Date dateStart, Date dateEnd, String pattern) {
        DateFormat df = new SimpleDateFormat(pattern);
        try {
            String dateStartStr = DateUtil.date2String(dateStart, pattern);
            String dateEndStr = DateUtil.date2String(dateEnd, pattern);
            Date dt1 = df.parse(dateStartStr);
            Date dt2 = df.parse(dateEndStr);
            if (dt1.getTime() > dt2.getTime()) {
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    public static int monthSpace(Date dateStart, Date dateEnd) throws ParseException {
        Calendar bef = Calendar.getInstance();
        Calendar aft = Calendar.getInstance();
        bef.setTime(dateEnd);
        aft.setTime(dateStart);
        int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
        return result + month;
    }


    public static Date stringToDate(String str) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            logger.error("DateUtil   stringToDate方法出错，异常信息为:", e);
        }
        return date;
    }

    public static Date stringToDate(String dateStr, String formatStr) {
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        DateFormat format = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            logger.error("DateUtil   stringToDate方法出错，异常信息为:", e);
        }
        return date;
    }

    /**
     * 判断是否是当天
     *
     * @param date
     * @return
     */
    public static boolean isToday(Date date) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date);
        int year1 = c1.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH) + 1;
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(new Date());
        int year2 = c2.get(Calendar.YEAR);
        int month2 = c2.get(Calendar.MONTH) + 1;
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        if (year1 == year2 && month1 == month2 && day1 == day2) {
            return true;
        }
        return false;
    }

    /**
     * 计算月份之差
     *
     * @param beginDate
     * @param endDate
     * @param pattern
     * @return
     * @author 张小文
     */
    public static int getMonthSub(String beginDate, String endDate, String pattern) {
        String temp = beginDate;
        if (beginDate.compareTo(endDate) > 0) {
            beginDate = endDate;
            endDate = temp;
        }
        Calendar begin = Calendar.getInstance();
        begin.setTime(DateUtil.string2Date(beginDate, pattern));
        Calendar end = Calendar.getInstance();
        end.setTime(DateUtil.string2Date(endDate, pattern));
        int i = 0;
        if (begin.compareTo(end) != 0) {
            if (begin.get(Calendar.YEAR) == end.get(Calendar.YEAR))
                i = end.get(Calendar.MONTH) - begin.get(Calendar.MONTH);
            else {
                if (end.get(Calendar.MONTH) - begin.get(Calendar.MONTH) >= 0) {
                    i = end.get(Calendar.MONTH) - begin.get(Calendar.MONTH) + (end.get(Calendar.YEAR) - begin.get(Calendar.YEAR)) * MONTHS_ONE_YEAR;
                } else {
                    i = (MONTHS_ONE_YEAR + end.get(Calendar.MONTH) - begin.get(Calendar.MONTH)) + (end.get(Calendar.YEAR) - begin.get(Calendar.YEAR) - 1) * MONTHS_ONE_YEAR;
                }
            }
        }
        return i;
    }

    /**
     * 根据身份证生成出生日期
     */
//    public static Calendar GetBirthdatByIdCode(String idCode) {
//        String tmpStr = "";
//        Calendar calendar = Calendar.getInstance();
//        if (!ValidateUtil.isEmpty(idCode)) {
//            if (idCode.trim().length() == 18) {
//                tmpStr = idCode.substring(6, 14);
//                calendar.set(Integer.valueOf(tmpStr.substring(0, 4)), Integer.valueOf(tmpStr.substring(4, 6)) - 1, Integer.valueOf(tmpStr.substring(6)));
//            } else if (idCode.trim().length() == 15) {
//                tmpStr = idCode.substring(6, 12);
//                tmpStr = "19" + tmpStr;
//                calendar.set(Integer.valueOf(tmpStr.substring(0, 4)), Integer.valueOf(tmpStr.substring(4, 6)) - 1, Integer.valueOf(tmpStr.substring(6)));
//            }
//        }
//        return calendar;
//    }


    public static String getTimeStamp() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String str = sdf.format(date);
        return str;
    }

    /**
     * 根据身份证和时间生成年龄
     */
//    public static int getAgeByIdCode(String idCode, Date date) {
//        Calendar birthday = GetBirthdatByIdCode(idCode);
//        int birthmonth = birthday.get(Calendar.MONTH) + 1;
//        int birthdate = birthday.get(Calendar.DATE);
//
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        int month = calendar.get(Calendar.MONTH) + 1;
//        int day = calendar.get(Calendar.DATE);
//
//
//        int age = calendar.get(Calendar.YEAR) - birthday.get(Calendar.YEAR) - 1;
//        if (birthmonth < month || birthmonth == month && birthdate <= day) {
//            age++;
//        }
//        return age;
//    }


    /**
     * @param @param  date
     * @param @return 参数
     * @return int    返回类型
     * @throws
     * @Title: getHours
     * @Description: 获取小时
     * @author 刘勇
     */
    public static int getHours(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化当前时间
        String dateStr = dateFormat.format(date);
        int hours = Integer.valueOf(dateStr.substring(11, 13));
        return hours;
    }

    /**
     * @param @param  smdate
     * @param @param  bdate
     * @param @return
     * @param @throws ParseException    参数
     * @return int    返回类型
     * @throws
     * @Title: daysBetween
     * @Description: 计算俩个日期之间的天数
     * @author 刘勇
     */
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        String formatSmdate = DateUtil.formatDataStrToLy(smdate).replace("年", "-").replace("月", "-").replace("日", "-");
        String formatBdate = DateUtil.formatDataStrToLy(bdate).replace("年", "-").replace("月", "-").replace("日", "-");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(formatSmdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(formatBdate));
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        Calendar scal = Calendar.getInstance();
        scal.setTime(bdate);

        Calendar bcal = Calendar.getInstance();
        bcal.setTime(smdate);

        int day1 = scal.get(Calendar.DAY_OF_YEAR);
        int day2 = bcal.get(Calendar.DAY_OF_YEAR);

        int year1 = scal.get(Calendar.YEAR);
        int year2 = bcal.get(Calendar.YEAR);
        if (year1 != year2) {  //同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {  //闰年
                    timeDistance += 366;
                } else {  //不是闰年

                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else { //不同年
            return day2 - day1;
        }

    }

    /**
     * 日期矫正
     *
     * @param dateStr
     * @return
     * @throws ParseException
     */
    public static String formatDataStrToLy(String dateStr) throws ParseException {
        Date date = new SimpleDateFormat("yyyy年MM月dd日").parse(dateStr);
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int year = instance.get(Calendar.YEAR);
        int month = instance.get(Calendar.MONTH) + 1;
        int day = instance.get(Calendar.DAY_OF_MONTH);
        if (month <= 9) {
            if (day <= 9) {
                return String.valueOf(year) + "年" + "0" + String.valueOf(month) + "月" + "0" + String.valueOf(day) + "日";
            }
            return String.valueOf(year) + "年" + "0" + String.valueOf(month) + "月" + day + "日";
        } else {
            if (day <= 9) {
                return String.valueOf(year) + "年" + String.valueOf(month) + "月" + "0" + String.valueOf(day) + "日";
            }
        }
        return String.valueOf(year) + "年" + String.valueOf(month) + "月" + day + "日";
    }


    /**
     * @param
     * @return
     * @description 获取当前月份的第一天
     * @author: xiaoying@hexindai.com V1.0 2017/12/4 14:04
     */
    public static String getMonthFirstDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 00:00:00");

        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取当前月份的最后一天
     * @author: xiaoying@hexindai.com V1.0 2017/12/4 14:04
     */
    public static String getMonthLastDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");

        return str.toString();
    }
    
    /**
	 * 秒转化为天小时分秒字符串  
	 * @author zhaohuanhuan V1.0 2018-1-23 下午5:10:34
	 * @param seconds
	 * @return String
	 */
    public static String formatSeconds(long seconds) {    
        String timeStr = seconds + "秒";    
        if (seconds > 60) {    
            long second = seconds % 60;    
            long min = seconds / 60;    
            timeStr = min + "分" + second + "秒";    
            if (min > 60) {    
                min = (seconds / 60) % 60;    
                long hour = (seconds / 60) / 60;    
                timeStr = hour + "小时" + min + "分" + second + "秒";    
                if (hour > 24) {    
                    hour = ((seconds / 60) / 60) % 24;    
                    long day = (((seconds / 60) / 60) / 24);    
                    timeStr = day + "天" + hour + "小时" + min + "分" + second + "秒";    
                }    
            }    
        }    
        return timeStr;    
    } 

    /**
     * @param
     * @return
     * @description 获取当天的前一天23:59:59
     * @author: xiaoying@hexindai.com V1.0 2017/12/21 11:59
     */
    public static String BeforeNowDay() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");
        return str.toString();
    }
     /**
       * @param
       * @return
       * @description 获取当天的前一天 00:00:00
       * @author: xiaoying@hexindai.com V1.0 2017/12/27 17:20
      */
    public static String BeforeNowDay2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 00:00:00");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取当前月份 减去输入number的月份第一天  比如 当前月份12-22 返回11-01
     * @author: xiaoying@hexindai.com V1.0 2017/12/22 17:44
     */
    public static String getFirstDayOfMonth(int subMonth) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - subMonth);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 00:00:00");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取当前月份 减去输入number的月份第一天  比如 当前月份12-22 返回11-01
     * @author: xiaoying@hexindai.com V1.0 2017/12/22 17:44
     */
    public static String getFirstLDayOfMonth(int subMonth) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - subMonth);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取当前月份 减去输入number 的月份 第最后一天  比如 当前月份12-22 返回11-30
     * @author: xiaoying@hexindai.com V1.0 2017/12/22 17:44
     */
    public static String getLastDayOfMonth(int subMonth) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        calendar.set(Calendar.MONTH, month - subMonth);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String s = sdf.format(calendar.getTime());
        StringBuffer str = new StringBuffer().append(s).append(" 23:59:59");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取当前月份 sub 输入值的月份  当前时间 2017-12  传1 返回 2017-11
     * @author: xiaoying@hexindai.com V1.0 2017/12/22 17:19
     */
    public static String BeforeOneMonth(int subMonth) {
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH);
        c.set(Calendar.MONTH, month - subMonth);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String time = format.format(c.getTime());
        return time;
    }

    /**
     * @param
     * @return
     * @description 获取某月的最后一天
     * @author: xiaoying@hexindai.com V1.0 2017/12/23 14:57
     */
    public static String getLastDayByYearAndMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month - 1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastDayOfMonth = sdf.format(cal.getTime());
        StringBuffer str = new StringBuffer().append(lastDayOfMonth).append(" 23:59:59");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 获取yyyy-MM 的第一天
     * @author: xiaoying@hexindai.com V1.0 2017/12/23 14:57
     */
    public static String getYMFistDayByTime(String time) {
        StringBuffer str = new StringBuffer().append(time).append("-01 00:00:00");
        return str.toString();
    }

    /**
     * @param
     * @return
     * @description 判断时间格式 格式必须为“YYYY-MM”2004-2-30 是无效的 2004-2 是无效的 2017-11 是有效的
     * @author: xiaoying@hexindai.com V1.0 2017/12/23 15:12
     */
    public static boolean isYMValidDate(String str) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM");
        try {
            Date date = formatter.parse(str);
            return str.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @param
     * @return
     * @description 根据时间获取年 已满足 yyyy-MM
     * @author: xiaoying@hexindai.com V1.0 2017/12/23 15:15
     */
    public static int getYearByTimeStr(String time) {
        return Integer.parseInt(time.substring(0, 4));
    }

    /**
     * @param
     * @return
     * @description  根据时间获取月 2017-01 返回1  2017-12 返回12  满足 yyyy-MM
     * @author: xiaoying@hexindai.com V1.0 2017/12/23 15:15
     */
    public static int getMonthByTimeStr(String time) {
        return Integer.parseInt(time.substring(5, 7));
    }

     /**
       * @param
       * @return
       * @description 判断当前是否是第一天
       * @author: xiaoying@hexindai.com V1.0 2017/12/27 16:58
      */
    public static boolean TodayisFirstDay(){
        // 获得一个日历对象
        Calendar c = Calendar.getInstance();
        // 得到本月的那一天
        int today = c.get(c.DAY_OF_MONTH);
        // 然后判断是不是本月的第一天
        if (today == 1) {
        //是
            return true;
        } else {
        //否
            return  false;
        }
    }
    /**
     * 获取当前时间上个 月的后一天
     * @param args
     * @throws ParseException 
     * @throws Exception
     */
    public static String getMonthAfterDay(String strDate) throws ParseException{
    	Calendar c = Calendar.getInstance();  
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	Date date=null;
    	date= new SimpleDateFormat("yyyy-MM-dd").parse(strDate);  
    	c.setTime(date); 
    	c.add(Calendar.MONTH, -1);    //得到前一个月    
    	c.add(Calendar.DAY_OF_MONTH, 1);
    	return format.format(c.getTime())+" 05:00:00"; 
    }

    public static void main(String[] args) throws Exception {
//        String firstDayOfMonth = getFirstDayOfMonth(10);
//        String lastDayOfMonth = getLastDayOfMonth(10);
//        String beforeOneMonth = BeforeOneMonth(10);
//        logger.info("ssssss" + firstDayOfMonth);
//        logger.info("ssssss" + lastDayOfMonth);
//        logger.info("ssssss" + beforeOneMonth);
//        String time = "2016-02";
//        if (isYMValidDate(time)) {
//            Integer year = Integer.parseInt(time.substring(0, 4));
//            Integer month = Integer.parseInt(time.substring(5, 7));
//            logger.info("year" + year);
//            logger.info("month" + month);
//            String lastDayByYearAndMonth = getLastDayByYearAndMonth(year, month);
//            String fistTime = getYMFistDayByTime(time);
//            logger.info("this year and this month  first day  is " + fistTime);
//            logger.info("this year and this month   last day  is " + lastDayByYearAndMonth);
//        } else {
//            logger.info("error");
//        }
        /*Date date = DateUtil.getDate("2016-02-01 00:00:00");
        logger.info("d");
        boolean b = TodayisFirstDay();
        logger.info(b+"d");*/
    	String monthAfterDay = getMonthAfterDay("2018-03-02");
    	//long daySub = getDaySub("2018-03-02","2018-04-02");
    	System.err.println(monthAfterDay);
    	
    }

    /**
     * 增加几年
     * @author wqf V1.0 2018年8月27日 下午2:58:20
     * @param yearNums 年数
     * @param simp 格式
     * @return String
     */
    public static String addSomeYears(Integer yearNums,String simp){
    	Calendar c = Calendar.getInstance();
    	c.add(Calendar.YEAR, yearNums);
    	return DateUtil.date2String(c.getTime(), simp);
    }
}
